﻿using MediatR;
using Sgr.Application.Commands;
using Sgr.Application.Queries;
using Sgr.Exceptions;
using Sgr.UPMS.Domain.Organizations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Organizations
{
    public class CreateOrgInvitationCommandHandler
        : IRequestHandler<CreateOrgInvitationCommand, CommandResult<string>>
    {
        private readonly IOrganizationManage _organizationManage;
        private readonly IOrganizationInvitationRepository _invitationRepository;
        private readonly ICurrentUser _currentUser;

        public CreateOrgInvitationCommandHandler(
            IOrganizationManage organizationManage,
            IOrganizationInvitationRepository invitationRepository,
            ICurrentUser currentUser)
        {
            _invitationRepository = invitationRepository;
            _organizationManage = organizationManage;
            _currentUser = currentUser;
        }

        public async Task<CommandResult<string>> Handle(
            CreateOrgInvitationCommand request,
            CancellationToken cancellationToken)
        {
            long orgId = QueryHelper.GetOrgId(_currentUser);

            // 创建邀请码
            var invitation = await _organizationManage.CreateInvitationAsync(
                orgId,
                TimeSpan.FromHours(request.ValidHours),
                request.UsageLimit,
                request.Description,
                cancellationToken);

            // 保存邀请码
            await _invitationRepository.InsertAsync(invitation, cancellationToken);

            // 返回
            return CommandResult.Success<string>(invitation.InvitationCode);
        }
    }
}